package com.foreveross.chameleon;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.*;
import android.os.Bundle;
import com.foreveross.chameleon.base.PushApplication;
import com.foreveross.chameleon.socket.PushRTx;
import com.foreveross.chameleon.socket.PushSetup;
import com.foreveross.chameleon.socket.ServicePush;
import com.foreveross.chameleon.utils.AppLog;
import com.foreveross.chameleon.utils.PackageUtil;
import com.foreveross.chameleon.utils.Preferences;
import com.foreveross.chameleon.utils.PushConstants;
import com.foreveross.chameleon.zillasdk.Zilla;
import com.foreveross.chameleon.zillasdk.ZillaDelegate;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONException;
import org.json.JSONObject;
import org.msgpack.type.Value;

/**
 * Created by zhouzhineng on 14-7-29.
 */
public class PushPlugin extends CordovaPlugin {

    public final static String TAG = "PushPlugin";

    public static final String REGISTER = "register";
    public static final String UNREGISTER = "unregister";
    public static final String EXIT = "exit";
    private static String MESSAGE_TYPE_KEY = "messageType";
    private static String MESSAGE_TYPE_MDM = "MDM";
    private static CordovaWebView gWebView;
    private static String gECB;
    private static String gSenderID;
    private static Bundle gCachedExtras = null;
    private static boolean gForeground = false;

    private Intent intent;

    private Context getApplicationContext() {
        return this.cordova.getActivity().getApplicationContext();
    }

    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        // TODO
        super.initialize(cordova, webView);
        gForeground = true;
        AppLog.i(" push 插件 启动....");
        register();
    }

    @Override
    public boolean execute(String action, String data, CallbackContext callbackContext) throws JSONException {
        System.out.println("push plugin");
        gWebView = this.webView;
        if (action.equals(REGISTER)) {
            register();
            String mdmCommand = "cordova.exec(null, null, \"PluginMdm\", \"active\", \"\");";
            gWebView.sendJavascript(mdmCommand);
        } else if (action.equals(UNREGISTER)) {
            unregister();
        } else if (action.equals(EXIT)) {

        }
        return super.execute(action, data, callbackContext);
    }

    public void register() {
        IntentFilter filter = new IntentFilter(PushConstants.ACTION_REC_MESSAGE);
        getApplicationContext().registerReceiver(receiver, filter);
        if (intent == null) {
            intent = new Intent(getApplicationContext(), ServicePush.class);
        }
        AppLog.d("PushPlugin---->register");
        PushSetup.getInstance().registerMsgInterceptor(new PushRTx.MsgInterceptor() {

            @Override
            public boolean isNeedToIntercept(byte[] msg) {
                try {
                    Value v = PackageUtil.byteToObject(msg);
                    JSONObject jsonObj = new JSONObject(v.toString());
                    AppLog.d("the mdmJson at isNeedToInterceptor is ===>" + jsonObj);
                    if (jsonObj.has(MESSAGE_TYPE_KEY)) {
                        if (MESSAGE_TYPE_MDM.equals(jsonObj.getString(MESSAGE_TYPE_KEY))) {
                            return true;
                        }
                    }
                } catch (JSONException e) {
                    // 无须处理，非mdm json
                }
                return false;
            }

            @Override
            public void handleMsg(byte[] msg) {
                //解析之类调用插件执行
                //try {
                Value v = PackageUtil.byteToObject(msg);
                //JSONObject jsonMdm = new JSONObject(v.toString());
                Intent intent = new Intent();
                intent.setAction("com.mdmlib.mdm.action_handle_mdm_msg");
                intent.putExtra("jsonMdm", v.toString());
                PushApplication.getApplication().sendBroadcast(intent);

                //} catch(JSONException e) {
                //    e.printStackTrace();
                //}
            }
        });
//        authentication();
        getApplicationContext().startService(intent);
    }

    public void unregister() {
        try {
            getApplicationContext().unregisterReceiver(receiver);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (intent != null) {
            getApplicationContext().stopService(intent);
        }

        AppLog.d("PushPlugin---->unregister");
    }


    @Override
    public void onPause(boolean multitasking) {
        super.onPause(multitasking);
        gForeground = false;
        final NotificationManager notificationManager = (NotificationManager) cordova.getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
    }

    @Override
    public void onResume(boolean multitasking) {
        super.onResume(multitasking);
        gForeground = true;
        IntentFilter filter = new IntentFilter(PushConstants.ACTION_REC_MESSAGE);
        getApplicationContext().registerReceiver(receiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        gForeground = false;
        gECB = null;
        gWebView = null;
        try {
            getApplicationContext().unregisterReceiver(receiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean isInForeground() {
        return gForeground;
    }

    public static boolean isActive() {
        return gWebView != null;
    }

    private void authentication() {
        final Context context = getApplicationContext();
        ZillaDelegate delegate = new ZillaDelegate() {

            @Override
            public void requestSuccess(String json) {
                try {
                    if (json.equals("403")) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                        builder.setTitle("提示");
                        builder.setMessage("应用验证失败");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }
                        );
                        Dialog dialog = builder.create();
                        dialog.show();
                    } else if (json.equals("400")) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                        builder.setTitle("提示");
                        builder.setMessage("应用已删除");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }
                        );
                        Dialog dialog = builder.create();
                        dialog.show();
                    } else {
                        JSONObject jb = new JSONObject(json);
                        String token = jb.getString("token");
                        String expired = jb.getString("expired");
                        // 保存token和expired
                        Preferences.saveToken(token, expired);
                        AppLog.e("save token and expired");
                        // mPush.register();
                        getApplicationContext().startService(intent);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void requestStart() {
                // TODO Auto-generated method stub
            }

            @Override
            public void requestFailed(String errorMessage) {
                //Toast.makeText(MainActivity.this, "应用验证失败，请检查网络", Toast.LENGTH_SHORT).show();
                AppLog.e("应用验证失败,请检查网络");
            }
        };
        Zilla.getZilla().appAuth(context, delegate);

    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(PushConstants.ACTION_REC_MESSAGE)) {
                String msg = intent.getStringExtra("msg");
                gWebView.sendJavascript("window.plugins.pushNotification.handlePushMsg(" + "\'"
                        + msg + "\'" + ");");
                /*try{
                    JSONObject json = new JSONObject(msg);
                    if(json.has("id")) {
                        String msgId = json.getString("id");
                        AppLog.d("the message Id == " + msgId);
                        receiptsMessage(getApplicationContext(),msgId);
                    }
                } catch(Exception e) {
                    e.printStackTrace();
                }*/

            }
        }
    };
}
